package ddz.logic;

import com.kaka.notice.annotation.Handler;
import com.kaka.util.IntMap;
import com.kaka.util.MathUtils;
import ddz.constants.Crypto;
import ddz.constants.OpCode;
import ddz.db.service.CensusService;
import ddz.net.LogicDataHandler;
import ddz.net.ProtocolMessage;
import ddz.numerical.manager.ConfPlaceInfoManager;
import ddz.numerical.pojo.ConfPlaceInfo;
import ddz.protos.GameChu;
import ddz.protos.GamePlace;

import java.util.List;

/**
 * 选择游戏玩法
 */
@Handler(cmd = OpCode.cmd_select_mode)
public class SelectModeHandler extends LogicDataHandler {
    @Override
    public void execute(ProtocolMessage msg) throws Exception {
        byte[] bytes = (byte[]) msg.getBody();
        GamePlace.CsSelectMode csSelectMode = GamePlace.CsSelectMode.parseFrom(bytes);
        int mode = csSelectMode.getMode();
        if (mode > 0) {
            ConfPlaceInfoManager confPlaceInfoManager = this.retrieveProxy(ConfPlaceInfoManager.class);
            List<ConfPlaceInfo> list = confPlaceInfoManager.getListByMode(mode);
            if (list == null) {
                return;
            }
        }
        CensusService censusService = this.retrieveProxy(CensusService.class);
        IntMap<IntMap<Integer>> countMap;
        if (mode <= 0) {
            countMap = censusService.query();
        } else {
            countMap = censusService.query(mode);
        }
        GamePlace.ScSelectMode.Builder builder = GamePlace.ScSelectMode.newBuilder();
        GamePlace.PlaceNumMap.Builder placeNumBuilder = GamePlace.PlaceNumMap.newBuilder();
        builder.setMode(mode);
        IntMap.Keys keys = countMap.keys();
        while (keys.hasNext) {
            int modeKey = keys.next();
            IntMap<Integer> placeNumMap = countMap.get(modeKey);
            if (placeNumMap != null && placeNumMap.size() > 0) {
                IntMap.Keys placeNumKeys = placeNumMap.keys();
                while (placeNumKeys.hasNext) {
                    int placeKey = placeNumKeys.next();
                    int count = placeNumMap.get(placeKey);
                    count = plusIllusoryNumber(placeKey, count);
                    placeNumBuilder.putNum(placeKey, count);
                }
                builder.putPlaceNumMap(modeKey, placeNumBuilder.build());
                placeNumBuilder.clear();
            }
        }
        this.sendData(msg.uid(), Crypto.isCrypto, opcode(), builder.build().toByteArray());
    }

    private int plusIllusoryNumber(int place, int count) {
        switch (place) {
            case 1:
                return count + MathUtils.random(400, 600);
            case 2:
                return count + MathUtils.random(300, 400);
            case 3:
                return count + MathUtils.random(100, 200);
            case 4:
                break;
        }
        return count + MathUtils.random(100, 200);
    }

}
